import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/models/report/selfReadingDto.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/grids/selfReadingDataGrid.dart';
import 'package:reactive_forms/reactive_forms.dart';

import 'reportsStudentPersonalContent.dart';

class ReportsStudentPersonalSelfReading extends StatefulWidget {
  ReportsStudentPersonalSelfReading({
    Key? key,
    required this.classId,
    required this.userName,
  }) : super(key: key);
  final String classId;
  final String userName;

  @override
  ReportsStudentPersonalSelfReadingState createState() =>
      ReportsStudentPersonalSelfReadingState();
}

ValidatorFunction _compareDate(String controlName, String matchingControlName) {
  return (AbstractControl<dynamic> control) {
    final form = control as FormGroup;

    final formControl = form.control(controlName);
    final matchingFormControl = form.control(matchingControlName);

    if (formControl.isNotNull &&
        formControl.value is DateTime &&
        matchingFormControl.isNotNull &&
        matchingFormControl.value is DateTime &&
        formControl.value!.isAfter(matchingFormControl.value!)) {
      matchingFormControl.setErrors({'compareDate': true});
      matchingFormControl.markAsTouched();
    } else {
      matchingFormControl.removeError('compareDate');
    }
    return null;
  };
}

class ReportsStudentPersonalSelfReadingState
    extends State<ReportsStudentPersonalSelfReading> {
  final ReportsController _reportsController = Get.find();
  var box = Hive.box('appconfig');

  final form = FormGroup({
    'from': FormControl<DateTime>(validators: [Validators.required]),
    'to': FormControl<DateTime>(validators: [Validators.required]),
    'recording': FormControl<bool>(),
    'writing': FormControl<bool>(),
  }, validators: [
    _compareDate('from', 'to'),
  ]);

  @override
  void initState() {
    studentPersonalReportTab = Constants.studentPersonalReportTabs[3];
    if (_reportsController.selfReadingData.value.list != null) {
      _reportsController.selfReadingData.value.list!.clear();
    }

    form.control('from').value = DateTime.now().add(Duration(days: -1 * 90));
    form.control('to').value = DateTime.now();
    form.control('recording').value = false;
    form.control('writing').value = false;
    fetchOverallData(
        widget.userName,
        form.control('from').value,
        form.control('to').value,
        form.control('recording').value,
        form.control('writing').value);
    super.initState();
  }

  void _onCustomTimeUpdate() {
    if (!form.valid) {
      form.markAllAsTouched();
      return;
    } else {
      fetchOverallData(
          widget.userName,
          form.control('from').value,
          form.control('to').value,
          form.control('recording').value,
          form.control('writing').value);
    }
  }

  void fetchOverallData(String userName, DateTime? start, DateTime? end,
      bool recording, bool writing) {
    int? newfrom = start != null ? start.millisecondsSinceEpoch : null;
    int? newto = end != null ? end.millisecondsSinceEpoch : null;

    SelfReadingDto dto = new SelfReadingDto(
        complete: true,
        start: newfrom,
        end: newto,
        onlyWithRecording: recording,
        onlyWithWriting: writing,
        progress: true);
    Future.delayed(Duration(milliseconds: 200), () {
      _reportsController.fetchSelfReading(userName, dto);
    });
  }

  void _onCustomTimeClear() {
    form.control('from').value = null;
    form.control('to').value = null;
    fetchOverallData(
        widget.userName,
        form.control('from').value,
        form.control('to').value,
        form.control('recording').value,
        form.control('writing').value);
  }

  void resetForm() {
    form.control('from').value = DateTime.now().add(Duration(days: -1 * 90));
    form.control('to').value = DateTime.now();
    form.control('recording').value = false;
    form.control('writing').value = false;
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build SchoolAdmin reportsStudentPersonal self reading');
    return Center(
        child: Column(children: [
      Row(
        children: [
          Expanded(
              child: ReactiveForm(
            formGroup: form,
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.symmetric(horizontal: 12.0),
                      width: 300,
                      child: ReactiveTextField<DateTime>(
                        formControlName: 'from',
                        //readOnly: true,
                        decoration: InputDecoration(
                          labelText: 'From'.tr,
                          labelStyle: Theme.of(context).textTheme.titleSmall,
                          suffixIcon: ReactiveDatePicker<DateTime>(
                            formControlName: 'from',
                            firstDate: DateTime(1990),
                            lastDate: DateTime.now(),
                            builder: (context, picker, child) {
                              return IconButton(
                                onPressed: picker.showPicker,
                                icon: const Icon(Icons.date_range),
                              );
                            },
                          ),
                        ),
                      ),
                    ),
                    Container(
                      width: 300,
                      margin: EdgeInsets.symmetric(horizontal: 12.0),
                      child: ReactiveTextField<DateTime>(
                        formControlName: 'to',
                        //readOnly: true,

                        decoration: InputDecoration(
                          labelText: 'To'.tr,
                          labelStyle: Theme.of(context).textTheme.titleSmall,
                          suffixIcon: ReactiveDatePicker<DateTime>(
                            formControlName: 'to',
                            firstDate: DateTime(1990),
                            lastDate: DateTime.now(),
                            builder: (context, picker, child) {
                              return IconButton(
                                onPressed: picker.showPicker,
                                icon: const Icon(Icons.date_range),
                              );
                            },
                          ),
                        ),
                        validationMessages: {
                          'compareDate': (error) =>
                              'Start date must before than end date',
                        },
                      ),
                    )
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 21.0),
                  child:
                      Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                    Row(children: [
                      ReactiveCheckbox(formControlName: 'recording'),
                      Text("Recording".tr)
                    ]),
                    Row(children: [
                      ReactiveCheckbox(formControlName: 'writing'),
                      Text("Writing".tr)
                    ]),
                    ReactiveFormConsumer(
                      builder: (context, form, child) {
                        return Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 12.0),
                          child: ElevatedButton(
                            child: Text('Go'.tr),
                            onPressed: _onCustomTimeUpdate,
                            style: ButtonStyle(
                              backgroundColor: MaterialStateProperty.all(
                                  Get.theme.primaryColorDark),
                            ),
                          ),
                        );
                      },
                    ),
                    ReactiveFormConsumer(
                      builder: (context, form, child) {
                        return ElevatedButton(
                          child: Text('Clear'.tr),
                          onPressed: _onCustomTimeClear,
                          style: ButtonStyle(
                            backgroundColor:
                                MaterialStateProperty.all(Colors.blueGrey),
                          ),
                        );
                      },
                    ),
                  ]),
                )
              ],
            ),
          )),
        ],
      ),
      Expanded(
        child: Container(
          height: 450.0,
          alignment: Alignment.center,
          child: _reportsController.obx(
            (data) {
              if (_reportsController.selfReadingData.value.list != null) {
                if (_reportsController.selfReadingData.value.list!.length ==
                    0) {
                  return Text('Data not available ...'.tr);
                }
                return SelfReadingDataGrid(
                    _reportsController.selfReadingData.value.list!,
                    widget.userName);
              } else {
                return Text("");
              }
            },
            // onLoading: Center(
            //     child: CircularProgressIndicator(
            //   backgroundColor: Get.theme.primaryColorDark,
            //   strokeWidth: 9.0,
            // )),
          ),
        ),
      )
    ]));
  }
}
